﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContactManager.Models;
using ContactManager.Models.Validation;
//NO NEED THERE IS A CONTROLER FACTORY CALLED FROM GLOBALASA
//using StructureMap;
using ContactManager.Models.ViewData;
using ContactManager.Models.Entities;
using log4net;

namespace ContactManager.Controllers
{
    public class ContactController : Controller
    {
        //DECLARE INTERFACES to SERVICES
        //NOT NEED TO INSTANCIATE INTERFACES TO THEIR IMPLEMENTATIONS
        //that is done by StructureMap (globalasa.aspx file)
        private readonly IContactManagerService _service;
        private IValidationService _validationService = null;
        private ModelStateDictionary modelState;
        //This testing log providers
        private static readonly ILog log4 = LogManager.GetLogger("GeneralLog");
            
        //NOT NEED DAFULT PARAMETERLESS CONTROLLER AS it is managed bt StructureMap
        //The one and only place that the concrete class ContactManagerRepository class is used
        //public ContactController() 
        //{
          //  _service = new ContactManagerService(
            //    new ModelStateWrapper(this.ModelState
              //  ));
        //}

        // public ContactController() : this(ObjectFactory.GetInstance<IContactManagerService>()) 
        //{
        //_service = new ContactManagerService(
        //       new ModelStateWrapper(this.ModelState
        //       )); 
        //}
        //public ContactController(IContactManagerService service, IValidationService validationService)
        //{
        //    _service = service;
        //    _validationService = validationService;
        //}

        //* This section if StructureMap working . It needs to set the service
        [StructureMap.DefaultConstructor]
        public ContactController(IContactManagerService service,IValidationService validationService)
        {
            _service = service;
            _validationService = validationService;
        }

       
        

        //ContactManagerRepository _service = new ContactManagerRepository();
        //
        // GET: /Home/

        public ActionResult Index(System.Guid? id)
        {
            // Get selected group
            ContactGroup selectedGroup;
            if (id != null) selectedGroup = _service.GetGroup((Guid)id);
            else selectedGroup = _service.GetFirstGroup();
            
            if(selectedGroup == null)return RedirectToAction("Index", "Group");

            // Normal Request
            if (!Request.IsAjaxRequest())
            {
                var model = new IndexModel
                {
                    Groups = _service.ListGroups(),
                    SelectedGroup = selectedGroup
                };
                return View("Index", model);
            }

            //Test
            if (log4.IsWarnEnabled) log4.Warn("Index working");
            return PartialView("ContactList", selectedGroup);

        }

        //
        // GET: /Home/Details/5
        [Authorize]
        public ActionResult Details(System.Guid id)
        {
            Contact contact = _service.GetContact(id);
            if (contact == null)     return View("NotFound");
            else return View(new ContactFormViewModel(contact,_service));
            
        }

         protected bool AddGroupsToViewData()
        {
            var groups = _service.ListGroups();
            ViewData["GroupId"] = new SelectList(groups, "Id", "Name",0);
            return groups.Count > 0;
        }
        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            //Guid sGuid= new Guid();
            Contact _newEmptyContact = new Contact();
            ContactFormViewModel cfvm = new ContactFormViewModel(_newEmptyContact,_service);
            var groups = _service.ListGroups();
            if (groups.Count > 0) return View("Create", cfvm);
            else return RedirectToAction("Index", "Group");
            //return View("Create");
        
        }       
        //
        // POST: /Home/Create

        [HttpPost,Authorize]
        public ActionResult Create(Contact contact)
        {
            ContactFormViewModel cFVM = new ContactFormViewModel(contact, _service);
            //VALIDATE CONTACT before sending it to service layer
            ValidationState vst = _validationService.Validate<Contact>(contact);

            if (!vst.IsValid)
            {
                modelState = this.ModelState;

                ControlerHelpers.AddModelStateErrors( ref vst, ref modelState);
                //View("Create",contact);
                return View(cFVM);
            }


            if (!ModelState.IsValid) return View(cFVM);
            try
            {
                // TODO: Add insert logic here
                
                if(_service.Add(contact)) return RedirectToAction("Index");
            }
            catch
            {
                return View(cFVM);
            }
            return View(cFVM);
        }
        
        //
        // GET: /Home/Edit/5
        [Authorize,HttpGet]
        public ActionResult Edit(System.Guid id)
        {
            //is actually userID
            Contact contact = _service.GetContact(id);
            //if(!contact.IsOwnBy(id)) return  View("InvalidOwner");



            //return View(new Contact(_service.GetContact(id)));
            return View(contact);
        }

        //
        // POST: /Home/Edit/5

        [HttpPost,Authorize]
        public ActionResult Edit(System.Guid id, Contact contact)
        {
            //Contact _contact = _service.GetContact(id);
            //if (!contact.IsOwnBy(id)) return View("InvalidOwner");
           // ValidationState vst = _validationService.Validate<Contact>(contact);

            //if (vst.IsValid)
            //{

                try
                {
                    // TODO: Add update logic here
                    //UpdateModel(contact);
                    _service.EditContact(contact);


                    return RedirectToAction("Details", new { id = contact.Id });
                }
                catch
                {
                    //foreach (ValidationError error in vst.Errors)
                    //{
                    //    this.ModelState.AddModelError(error.Property, error.Message);
                    //}

                    return View(contact);
                }
            //}
           // foreach (ValidationError error in vst.Errors)
            //{
           //     this.ModelState.AddModelError(error.Property, error.Message);
           // }
            //return View(contact);
        }

        //
        // GET: /Home/Delete/5

        public ActionResult Delete(System.Guid id)
        {
            if (Request.IsAjaxRequest())
            {
                AjaxDelete(id);
            }
            Contact contact = _service.GetContact(id);
            //if (!contact.IsOwnBy(id)) return View("InvalidOwner");

            if (contact == null) return View("NoFounf");
            else return View(new ContactFormViewModel(contact,_service));
        }

        //
        // POST: /Home/Delete/5


        [AcceptVerbs(HttpVerbs.Delete)]
        [ActionName("DeleteContactViaAjax")]
        public ActionResult AjaxDelete(System.Guid id)
        {
            // Get contact and group
            var contactToDelete = _service.GetContact(id);
            var selectedGroup = _service.GetGroup(contactToDelete.ContactGroup.Id);

            // Ajax Request
            if (Request.IsAjaxRequest())
            {
                // Delete from database
                _service.DeleteContact(contactToDelete);

                // Return Contact List
                return PartialView("ContactList", selectedGroup); 
            }

            return View();
        }

        [HttpPost,Authorize]
        public ActionResult Delete(System.Guid id, string confirmButton)
        {

            Contact contact = _service.GetContact(id);
            //if (!contact.IsOwnBy(id)) return View("InvalidOwner");

            if (contact == null) return View("NoFound");
       
            try
            {
                // TODO: Add delete logic here
                _service.DeleteContact(contact);
                return View("Deleted");
            }
            catch
            {
                return View("Delete");
            }
        }

        
    }
    
}
